package com.ybb.vue.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ybb.vue.common.Result;
import com.ybb.vue.common.util.OperationRecordsUtils;
import com.ybb.vue.domain.dto.EpmAlarmRuleDto;
import com.ybb.vue.entity.EpmAlarmRule;
import com.ybb.vue.entity.SysUser;
import com.ybb.vue.mapper.SysUserMapper;
import com.ybb.vue.service.EpmAlarmRuleService;
import com.ybb.vue.mapper.EpmAlarmRuleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author apple
* @description 针对表【epm_alarm(防疫_告警管理)】的数据库操作Service实现
* @createDate 2023-03-21 20:41:13
*/
@Service
public class EpmAlarmRuleServiceImpl extends ServiceImpl<EpmAlarmRuleMapper, EpmAlarmRule>
implements EpmAlarmRuleService {

    @Autowired
    private EpmAlarmRuleMapper epmAlarmRuleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public Result save(EpmAlarmRuleDto epmAlarmRuleDto) {
        EpmAlarmRule epmAlarmRule = epmAlarmRuleMapper.selectOne(new QueryWrapper<EpmAlarmRule>().lambda().eq(EpmAlarmRule::getAlarmName, epmAlarmRuleDto.getAlarmName()));
        if (epmAlarmRule != null) {
            return Result.error("-1", "该告警规则已存在！");
        }
        EpmAlarmRule epmAlarmRuleInsert = new EpmAlarmRule();
        BeanUtils.copyProperties(epmAlarmRuleDto, epmAlarmRuleInsert);
        // 添加人
        epmAlarmRuleInsert.setEditor(SecurityContextHolder.getContext().getAuthentication().getName());
        // 根据通知对象 写入对应的邮箱地址
        String[] notices = epmAlarmRuleInsert.getNoticeObject().split(",");
        List<String> noticeList = new ArrayList<String>(Arrays.asList(notices));
        List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>().lambda().in(SysUser::getUsername, noticeList));
        String emails = userList.stream().map(r -> r.getEmail()).collect(Collectors.joining(","));
        epmAlarmRuleInsert.setEmail(emails);
        this.save(epmAlarmRuleInsert);

        // 操作记录
        String content = "操作了告警规则表，【新增】了1条记录，记录id为：" + epmAlarmRuleDto.getId();
        OperationRecordsUtils.createOperationRecords(content);
        return Result.success();
    }
}
